Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Count the Number of Good Subarrays

Problem Statement

Given an array of integers nums, and an integer k, find the count of "good" subarrays within nums.

A subarray is considered "good" if it contains at least k pairs of elements (i, j) where i < j and nums[i] == nums[j].

A subarray is a contiguous sequence of elements in the original array.

Examples

  • Example 1:

    • Input: nums = [2, 2, 2, 3, 3], k = 3
    • Expected Output: 3
    • Justification: There are 3 good subarrays that meet the criteria: [2, 2, 2, 3], [2, 2, 2, 3, 3], and [2, 2, 2]. Each of these subarrays has at least 3 pairs of equal elements.
  • Example 2:

    • Input: nums = [4, 4, 4, 4], k = 6
    • Expected Output: 1
    • Justification: The only good subarray that meets the criteria is the entire array itself [4, 4, 4, 4], which contains 6 pairs of equal elements.
  • Example 3:

    • Input: nums = [1, 2, 3, 1, 2], k = 2
    • Expected Output: 2
    • Justification: There is only 1 good subarray, which is [1, 2, 3, 1, 2]. It contains at least 2 pairs of equal elements.

Solution

To solve this problem, an efficient strategy utilizing a sliding window technique alongside a frequency map is employed to meticulously count the subarrays fulfilling the criterion of containing at least k pairs of identical elements. This method hinges on dynamically adjusting the boundaries of the window to encompass various segments of the array, methodically tracking the occurrence of each element to ascertain the formation of pairs. As the window expands, it meticulously updates the pair count, ensuring that each segment's potential to meet the specified condition is fully explored.

The effectiveness of this approach is underscored by its capacity to seamlessly navigate through the array, leveraging the frequency map for swift updates and checks on pair formation. This optimization minimizes redundant computations, thereby enhancing efficiency. By judiciously adjusting the window's size based on the evolving pair count, the algorithm ensures a comprehensive evaluation of all possible subarrays, accurately identifying those that qualify as "good" by the problem's standards.

Step-by-Step Algorithm

  1. Initialize Variables: Start with two pointers, i = 0 and j = 0, a long counter ans = 0 for the answer, a long counter count = 0 for the number of pairs, and n = nums.length for the size of the input array. Also, initialize a frequency map m.

  2. Iterate Through the Array: Loop through the array with j from 0 to n - 1. For each element nums[j], increment its frequency in the map m.

  3. Update Pair Count: If the frequency of nums[j] after incrementing is more than 1, it forms pairs. Increment count by m[nums[j]] - 1, which represents the new pairs formed by adding the current element.

  4. Check and Adjust Window: While count >= k (the subarray has enough pairs) and i <= j, calculate the number of new good subarrays that can be formed with the current j by adding n - j to ans. Then, decrement the frequency of nums[i] as i moves forward. If nums[i]'s frequency is still at least 1, decrement count by m[nums[i]] because moving i means losing some pairs. Increment i to shrink the window from the start.

  5. Return Answer: Once the loop completes, return ans as the total count of good subarrays found.

Algorithm Walkthrough

Let's consider the Input [2, 2, 2, 3, 3], k = 3

  1. Initialization:

    • Set i = 0 to mark the start of the sliding window.
    • Initialize ans = 0 to keep track of the total count of good subarrays.
    • Initialize count = 0 to track the current number of pairs within the window.
    • Determine n = 5 as the size of the input array.
    • Create a frequency map m to track the occurrences of each number within the current window.
  2. First Iteration (j = 0):

    • Process the first element, 2. The frequency map is updated to {2: 1}. No pairs are formed yet, so count remains at 0.
  3. Second Iteration (j = 1):

    • Process the second element, 2. The frequency map updates to {2: 2}. We now have one pair of 2s, incrementing count by 1 (count = count + 2 - 1 = 0 + 2 - 1 = 1).
  4. Third Iteration (j = 2):

    • Add another 2 to m. m = {2: 3}, count = count + 3 - 1 = 1 + 3 - 1 = 1.
    • Now, count is equal to k(3) and i<=j. So, execute the inner loop.
      • ans = ans + n - j = 0 + 5 - 2 = 3
      • Update the map to {2: 2}.
      • Update the count to count(3) - (m[2](3) - 1) = 3 - 2 = 1.
      • increment i to 1.
  5. Fourth Iteration (j = 3):

    • Add 3 to m. m = {2: 2, 3: 1}, count remains 1.
  6. Fifth Iteration (j = 4):

    • Add another 3 to m. m = {2: 3, 3: 2}, count increases to 2.
  7. Final Answer:

    • ans = 3 is the total count of good subarrays found.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

  • Time Complexity: The overall time complexity of the solution is . This is because the solution uses two nested loops to explore all possible subarrays of the input array, where n is the length of the input array. Within the inner loop, operations such as updating the frequency map and calculating the number of pairs have a time complexity of per iteration, but the repeated calculation for each subarray leads to the quadratic time complexity.

  • Space Complexity: The space complexity is for all solutions. This is due to the use of a hash map (or dictionary in Python) to count the frequency of elements within each subarray. In the worst case, if all elements of the array are distinct, the space required for the frequency map would be proportional to the size of the subarray being considered, which can be up to n in size.

Count the Number of Good Subarrays (medium)
Minimum Suffix Flips (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis